package com.eascs.admin.o2o.operation.controller;

import java.text.DecimalFormat;
import java.text.Format;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.common.o2o.O2oService;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.operation.form.OperationForm;
import com.eascs.admin.o2o.operation.operations.Operation;
import com.eascs.app.context.ConfigContext;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.dao.sql.ObjectSqlBuilder;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.assertion.util.AssertErrorUtils;
import com.eascs.common.util.ApplicationContextUtil;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.ViewContext;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.service.sys.SysOrgService;

@Controller
public class OperationController extends BaseMasterViewController {
	@Reference
	SysOrgService sysOrgService;
	@Override
	public void preHandle() {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "loanManage1");
	}
	private static Logger logger = LoggerFactory.getLogger(OperationController.class);

	@Inject
	private O2oService O2oService;

	private static Map<String, Operation> afterLoadOperationMap = null;

	@RequestMapping(value = "/o2o/operation/{operation}")
	public String operation(OperationForm operationForm, @PathVariable String operation) {
		AssertErrorUtils.assertHasText(operation, "operation must not null");
		logger.debug("operation={}", operation);
		logger.debug("afterLoadOperationForm={}", operationForm);
		if (null == afterLoadOperationMap)
			this.initAfterLoadOperations();
		Operation afterLoadOperation = afterLoadOperationMap.get(operation);
		AssertErrorUtils.assertNotNull(afterLoadOperation, "can't load afterLoadOperation operation={}", operation);
		
		String sql=afterLoadOperation.getSql();
//		logger.info("operation:sql={}", sql);
		if ("refinance".equals(operation)) {
			List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
			String no="";
			if (users!=null) {
				for (User user : users) {
					no+=user.getNo()+",";
				}
			}
			if (!"".equals(no)) {
				if (",".equals(no.substring(no.length()-1, no.length()))) {
					no=no.substring(0, no.length()-1);
				}
			}
			logger.info("refinance:userno={}", no);
			
			StringBuffer str =new StringBuffer();
			str.append("select l.loanapply_no,l.bill_code,u.user_full_name,CONCAT(left(u.document_no,3),'***',right(u.document_no,3)) as document_no,CONCAT(l.ltd_code,'-',l.ltd_name) as ltd,l.wf_type,l.bank_amount,l.payment_time,u.document_no as id_card from o2o_loanapply l INNER JOIN (select * from o2o_loan_user where  spouse_id is null and  sponsor_type is null )  u on u.loanapply_no=l.loanapply_no and  l.loan_id=l.loan_id ");
			str.append(" where   l.islock='N' and  l.bank_amount is not null and l.payment_time is not null");
			
			str.append(" and (l.creat_ro="+UserHolder.getUser().getNo());
			if (!StringUtils.isEmpty(no)) {
				str.append(" or l.operator_no in ("+no+"))");
			}else {
				str.append(" or /**DATA_PERMISSION(l.LTD)**/ 1=1 ) ");
			}
			
			str.append(" and l.wf_type in ('O','HN','YQ','DC')  and l.loan_flg='Y'");
			sql=str.toString();
		}
		
		ObjectSqlBuilder objectSqlBuilder = ObjectSqlBuilder.create(operationForm, ConfigContext.getStringValue(sql, sql));
		
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, 10, operationForm.getPageIndex());
		sqlPageQuery.setQuerySql(objectSqlBuilder.getSql());
		sqlPageQuery.addParams(objectSqlBuilder.getParams());
		PageResult<Object[]> pageResult = O2oService.findDataWithPage(sqlPageQuery);
		
//		logger.info("operation:sql1={}", ConfigContext.getStringValue(afterLoadOperation.getSql(), afterLoadOperation.getSql()));
//		logger.info("operation:sql2={}", sqlPageQuery);
		
		PaginationInfo paginationInfo = afterLoadOperation.buildPaginationInfo(pageResult);
//		paginationInfo.setTitleButtons(null);
		paginationInfo.setFormats(new Format[] { null, null,null, null, null,new DecimalFormat(",##0.00"),null });
		ViewContext.put("operationForm", operationForm);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("title", afterLoadOperation.getTitle());
		ViewContext.put("formUrl", com.eascs.web.context.RequestContext.getRequestURI());
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, afterLoadOperation.getMenuCode());
		return afterLoadOperation.getView();
	}

	private void initAfterLoadOperations() {
		Map<String, Operation> map = new HashMap<>();
		List<Operation> afterLoadOperations = ApplicationContextUtil.getBeans(Operation.class);
		for (Operation afterLoadOperation : afterLoadOperations) {
			map.put(afterLoadOperation.getOperation(), afterLoadOperation);
		}
		afterLoadOperationMap = map;
	}

}
